$(document).ready(function () {
	var socketServer = 'http://localhost:7070';
	var socket = io.connect(socketServer);
	
	
	socket.emit('horarioPopularRequest',document.getElementById('userId').value);
	socket.emit('tiposDeportesRequest',document.getElementById('userId').value);
	socket.emit('caloriasMensualesRequest',document.getElementById('userId').value);
	socket.emit('caloriasDeportesRequest',document.getElementById('userId').value);
	
	socket.on('horarioPopularData', function (json) {
		var  horarios=[];
		var jsonParsed = JSON.parse(json);
		var nroEntradas = jsonParsed.entradas.split(",");
        var hora = jsonParsed.horaEjercitadas.split(",");

        for (var i = nroEntradas.length - 1; i >= 0; i--) {
        	temp = [];
        	temp[0] = hora[i];
        	temp[1] = nroEntradas[i];
        	horarios[i] = temp;
        }
        
        plot_horarioChart(horarios);
		
    });
	
	socket.on('tiposDeportesData', function (json) {
		var data=[];
		var jsonParsed = JSON.parse(json);
		var nroEntradas = jsonParsed.entradas.split(",");
        var tipo = jsonParsed.nombre.split(",");

        for (var i = nroEntradas.length - 1; i >= 0; i--) {
        	data[i] = { label: tipo[i], data: nroEntradas[i] }
        }
        
        plot_tipoDeporteChart(data);
		
    });
	
	socket.on('caloriasDeportesData', function (json) {
		var data=[];
		var jsonParsed = JSON.parse(json);
		var nroEntradas = jsonParsed.calorias.split(",");
        var tipo = jsonParsed.nombre.split(",");

        for (var i = nroEntradas.length - 1; i >= 0; i--) {
        	data[i] = { label: tipo[i], data: nroEntradas[i] }
        }
        
        plot_caloriasDeporteChart(data);
		
    });
	
	
	socket.on('caloriasMensualesData', function (json) {
		var data=[];
		
		var boxCaloriasTotales=[];
		var boxPuntajeTotales=[];
		
		var totalCalorias=0;
		var totalPuntaje=0;
		
		var jsonParsed = JSON.parse(json);
		var nroCalorias = jsonParsed.calorias.split(",");
        var time = jsonParsed.time.split(",");

        for (var i = nroCalorias.length - 1; i >= 0; i--) {
        	temp = [];
        	temp[0] = time[i];
        	temp[1] = nroCalorias[i];
        	data[i] = temp;
        	
        	boxCaloriasTotales[i] =parseInt(nroCalorias[i]); 
        	boxPuntajeTotales[i] = (parseInt(nroCalorias[i]) * 2); 
        	
        	totalCalorias = totalCalorias + parseInt(temp[1]);
        	totalPuntaje = totalPuntaje + ( parseInt(temp[1]) * 2);
        }
        
        plot_caloriasMensualesChart(data);
        
        document.getElementById("puntajeTotales").innerHTML = totalPuntaje;
        document.getElementById("caloriasTotales").innerHTML = totalCalorias;
        
        $('.boxchartPuntaje').sparkline(boxPuntajeTotales, { type: 'bar', width:100});
        $('.boxchartCalorias').sparkline(boxCaloriasTotales, { type: 'bar', width:100}); 
    });
	

	function plot_caloriasMensualesChart(d) {

		for (var i = 0; i < d.length; ++i) {
			d[i][0] = d[i][0] * 1000;
		}
		
		// helper for returning the weekends in a period
		
		function weekendAreas(axes) {

			var markings = [],
				d = new Date(axes.xaxis.min);

			// go to the first Saturday

			d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
			d.setUTCSeconds(0);
			d.setUTCMinutes(0);
			d.setUTCHours(0);

			var i = d.getTime();

			// when we don't set yaxis, the rectangle automatically
			// extends to infinity upwards and downwards

			do {
				markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
				i += 7 * 24 * 60 * 60 * 1000;
			} while (i < axes.xaxis.max);

			return markings;
		}

		var options = {
			xaxis: {
				mode: "time",
				timeformat: "%d/%m/%y"
			},
			selection: {
				mode: "x"
			},
			grid: {
				markings: weekendAreas
			}
		};

		var plot = $.plot("#placeholder", [d], options);

		var overview = $.plot("#overview", [d], {
			series: {
				lines: {
					show: true,
					lineWidth: 1
				},
				shadowSize: 0
			},
			xaxis: {
				mode: "time"
			},
			yaxis: {
				min: 0,
				autoscaleMargin: 0.1
			},
			selection: {
				mode: "x"
			}
		});

		// now connect the two

		$("#placeholder").bind("plotselected", function (event, ranges) {

			// do the zooming

			plot = $.plot("#placeholder", [d], $.extend(true, {}, options, {
				xaxis: {
					min: ranges.xaxis.from,
					max: ranges.xaxis.to
				}
			}));

			// don't fire event on the overview to prevent eternal loop

			overview.setSelection(ranges, true);
		});

		$("#overview").bind("plotselected", function (event, ranges) {
			plot.setSelection(ranges);
		});

	}

	
	function plot_caloriasDeporteChart(data) {
		$.plot($(".caloriasDeportes"), data,
		{
		        series: {
		            pie: { 
		                innerRadius: 0.5,
		                show: true,
		                label: {
		                    show: true,
		                    radius: 2/3,
		                    formatter: function(label, series){
		                        return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+'<br/>'+Math.round(series.percent)+'%</div>';
		                    },
		                    threshold: 0.1
		                }
		            }
		        }
		});
	}
	
	
	function plot_tipoDeporteChart(data) {
		$.plot($(".tiposDeportes"), data,
		{
		        series: {
		            pie: { 
		                innerRadius: 0.5,
		                show: true,
		                label: {
		                    show: true,
		                    radius: 2/3,
		                    formatter: function(label, series){
		                        return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+'<br/>'+Math.round(series.percent)+'%</div>';
		                    },
		                    threshold: 0.1
		                }
		            }
		        }
		});
	}
	
	function plot_horarioChart(horarios) {
		if($(".chart-horarioPopular").length){
			
			$(".chart-horarioPopular").each(function(){
				
			var chartColor = $(this).parent().parent().css("color");
			
			var plot = $.plot($(".chart-horarioPopular"),
				   [ { data: horarios ,label: "Horarios"} ], {
					   series: {
						   lines: { 
								show: true,
								lineWidth: 3, 
								fill: false
						   },
						   points: { 
								show: true, 
								lineWidth: 3,
								fill: true,
								fillColor: chartColor 
						   },	
						   shadowSize: 2
					   },
					   grid: { hoverable: true, 
							   clickable: true, 
							   tickColor: "rgba(255,255,255,.15)",
							   borderColor: "rgba(255,255,255,0)",
							 },
					   legend: {
							show: false
					   		 },	
					   colors: ["#c7cbd5"],
					   xaxis: {
							font: {
							    color: "#c7cbd5"
							},
							ticks:6, 
							tickDecimals: 0, 
							tickColor: chartColor,
					   },
					   yaxis: {
							font: {
							    color: "#c7cbd5"
							},
							ticks:4, 
							tickDecimals: 0,
							autoscaleMargin: 0.000001
					   },
					 });
	
			function showTooltip(x, y, contents) {
				$('<div id="tooltip">' + contents + '</div>').css( {
					position: 'absolute',
					display: 'none',
					top: y + 5,
					left: x + 5,
					border: '1px solid #fdd',
					padding: '2px',
					'background-color': '#dfeffc',
					opacity: 0.80
				}).appendTo("body").fadeIn(200);
			}
	
			var previousPoint = null;
			$(".chart-horarioPopular").bind("plothover", function (event, pos, item) {
				$("#x").text(pos.x.toFixed(2));
				$("#y").text(pos.y.toFixed(2));
	
					if (item) {
						if (previousPoint != item.dataIndex) {
							previousPoint = item.dataIndex;
	
							$("#tooltip").remove();
							var x = item.datapoint[0].toFixed(2),
								y = item.datapoint[1].toFixed(2);
	
							showTooltip(item.pageX, item.pageY,
										item.series.label + " of " + x + " = " + y);
						}
					}
					else {
						$("#tooltip").remove();
						previousPoint = null;
					}
			});
			
		});
		
		}
	}
	
	
	
});